from flask import Flask, request, jsonify, Response
# import sqlalchemy
from flask_cors import CORS, cross_origin
import pymysql
import logging

app = Flask(__name__)

# 配置日志
logging.basicConfig(level=logging.DEBUG)
CORS(app, supports_credentials=True)

DBHOST = 'localhost'
DBUSER = 'root'
DBPASS = '666666'
DBNAME = 'my_database'

super_user = {
    "username": "123",
    "password": "666",
}


# @app.route('/')
# def index():
#     return 'Hello Flask!!!'

# class employee:


@app.route('/login', methods=['GET'])
def login():
    username = request.args.get('username')
    password = request.args.get('password')
    print(username, password)
    if username == super_user['username'] and password == super_user['password']:
        return jsonify({"success": True, "msg": "Username and password are required"}), 200


@app.route('/emp', methods=['GET'])
def data_get():
    cur, conn = contect()  # 获取游标对象和数据库连接对象
    sqlQuery = "select * from employees"
    cur.execute(sqlQuery)
    data = cur.fetchall()
    cur.close()  # 关闭游标
    conn.close()  # 关闭数据库连接
    return jsonify(data)


def contect():
    db = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
    print('数据库连接成功!')
    cur = db.cursor()
    # cur.close()
    return cur, db


@app.route('/emp/<string:id>', methods=['DELETE'])
def delete_employee(id):
    print("111")
    # id = request.args.get('id')
    print(id)
    cur, db = contect()
    sql_query = "DELETE FROM employees WHERE name = %s"
    cur.execute(sql_query, (id,))
    db.commit()
    # conn.commit()
    # conn.close()
    print("删除成功啦")

    data = data_get

    return jsonify({'success': True, 'message': 'Employee deleted'})
    # return jsonify({'success': True, 'message': 'Employee deleted'})


@app.route('/emp', methods=['GET'])
def data_inquie():
    name = request.args.get('name', '')


@app.route('/emp/search')
def search_emp():
    name = request.args.get('name', '')
    gender = request.args.get('gender', '')
    print("name:" + name + ",gender:" + gender)
    cur, db = contect()
    sql_query = "SELECT * FROM employees WHERE name LIKE %s AND gender = %s"

    cur.execute(sql_query, (f'%{name}%', gender))
    result = cur.fetchall()
    print(result)
    return jsonify(result)


if __name__ == "__main__":
    CORS(app)
    app.run(debug=True)
